package com.springcloud.utils;


import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


public class HttpPostHelper {
//    private static final HttpPostHelper instance = new HttpPostHelper();
//    public static HttpPostHelper getInstance() {
//        return instance;
//    }

    private static OkHttpClient okHttpClient = null;

    public synchronized static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            //缓存目录
//            File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");
//            int cacheSize = 10 * 1024 * 1024;
//            //OkHttp3拦截器
//            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
//                @Override
//                public void log(String message) {
//                    Log.i("xxx", message.toString());
//                }
//            });
//            //Okhttp3的拦截器日志分类 4种
//            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            okHttpClient = new OkHttpClient.Builder()
                    //添加OkHttp3的拦截器
//                    .addInterceptor(httpLoggingInterceptor)
//                    .addNetworkInterceptor(new CacheInterceptor())
                    .connectTimeout(20, TimeUnit.SECONDS)
                    .readTimeout(20, TimeUnit.SECONDS)
//                    .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))
                    .build();
        }
        return okHttpClient;
    }


    public static String syncPostJson(String strUrl, String data) {
        try {
            RequestBody body = RequestBody.create(data, MediaType.parse("application/json;charset=utf-8"));
            Request request = new Request.Builder().url(strUrl).post(body).build();
            return getOkHttpClient().newCall(request).execute().body().string();
        } catch (IOException e) {
            e.printStackTrace();

        }
        return "";
    }

    public static void asyncPostJson(final String strUrl, final String data, final Callback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    RequestBody body = RequestBody.create(data, MediaType.parse("application/json;charset=utf-8"));
                    Request request = new Request.Builder().url(strUrl).post(body).build();
                    getOkHttpClient().newCall(request).enqueue(callback);
                } catch (Exception e) {

                }
            }
        }).start();
    }

    public static String syncGet(String strUrl, String data) {
        try {
            Request resquest = new Request.Builder().url(strUrl).get().build();
            return getOkHttpClient().newCall(resquest).execute().body().string();
        } catch (IOException e) {
            e.printStackTrace();

        }
        return "";
    }

}
